"use client";

import React from "react";
import { LoginForm, ProForm, ProFormText } from "@ant-design/pro-form";
import { message } from "antd";
import { LockOutlined, UserOutlined } from "@ant-design/icons";
import { userLoginUsingPost } from "@/api/userController";
import { useRouter } from "next/navigation";
import Link from "next/link";
import Image from "next/image";
import { AppDispatch } from "@/stores";
import { setLoginUser } from "@/stores/loginUser";
import { useDispatch } from "react-redux";
import "./index.css";
import FunRiceUser = API.FunRiceUser;
import { queryFriendMessageRequestUsingPost } from "@/api/userRelationshipController";

/**
 * 用户登录页面
 * @param props
 */
const UserLoginPage: React.FC = (props) => {
  const [form] = ProForm.useForm();
  const router = useRouter();
  const dispatch = useDispatch<AppDispatch>();

  /**
   * 提交
   * @param values
   */
  const doSubmit = async (values: API.UserLoginRequest) => {
    try {
      const res = await userLoginUsingPost(values);
      if (res.data) {
        message.success("登录成功");
        // 保存用户登录态
        dispatch(setLoginUser(res.data as FunRiceUser));
        
        // 初始化消息统计
        try {
          const { data: friendRequests } = await queryFriendMessageRequestUsingPost();
          const followCount = Array.isArray(friendRequests) ? friendRequests.length : 0;
          const commentCount = Array.isArray(friendRequests) ? friendRequests.length : 0;
          const thumbCount = Array.isArray(friendRequests) ? friendRequests.length : 0;
          const systemCount = Array.isArray(friendRequests) ? friendRequests.length : 0;
          
          // 计算总数
          const totalCount = commentCount + thumbCount + followCount + systemCount;
          
          window.dispatchEvent(new CustomEvent('updateNotificationCount', {
            detail: { 
              count: totalCount
            }
          }));
        } catch (error) {
          console.error('Failed to load message counts:', error);
        }

        // 清除表单
        form.resetFields();
        
        // 使用 window.location.href 进行跳转，这会触发完整的页面刷新
        window.location.href = '/mood';
      }
    } catch (e: any) {
      message.error(e.message);
    }
  };

  return (
      <div id="userLoginPage">
        <LoginForm<API.UserLoginRequest>
            form={form}
            logo={
              <Image 
                src="/assets/logo.png" 
                alt="饭点到了" 
                width={45} 
                height={45} 
                style={{ borderRadius: '8px' }}
              />
            }
            title={
              <div style={{ 
                color: '#152DA5', 
                fontSize: '24px',
                fontWeight: 500,
                marginLeft: '2px'
              }}>
                饭点到了
              </div>
            }
            subTitle="一个按时吃饭动态分享的交流圈"
            onFinish={doSubmit}
            submitter={{
              searchConfig: {
                submitText: "登录",
              },
              submitButtonProps: {
                style: {
                  backgroundColor: '#1890FF',
                  border: 'none',
                  width: '100%'
                }
              }
            }}
        >
          <ProFormText
              name="userAccount"
              fieldProps={{
                size: "large",
                prefix: <UserOutlined />,
              }}
              placeholder={"请输入饭点账号"}
              rules={[
                {
                  required: true,
                  message: "请输入饭点账号",
                },
              ]}
          />
          <ProFormText.Password
              name="userPassword"
              fieldProps={{
                size: "large",
                prefix: <LockOutlined />,
              }}
              placeholder={"请输入密码"}
              rules={[
                {
                  required: true,
                  message: "请输入密码",
                },
              ]}
          />
          <div
              style={{
                marginBlockEnd: 24,
                textAlign: "end",
              }}
          >
            还没有账号？
            <Link prefetch={false} href={"/user/register"}>
              去注册
            </Link>
          </div>
        </LoginForm>
      </div>
  );
};

export default UserLoginPage;
